<template>
  <div class="warehouse-overview">
    <h2 class="overview-title">仓库概览</h2>
    <!-- 新增导出报表按钮 -->
    <div style="text-align: right; margin-bottom: 20px; margin-right: 20px">
      <el-button type="primary" @click="exportInventoryReport">导出库存报表</el-button>
    </div>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="receive-goods-container">
          <h3>进货</h3>
          <el-form :model="receiveForm" label-width="120px">
            <el-form-item label="商品名称">
              <el-input v-model="receiveForm.goodsName"/>
            </el-form-item>
            <el-form-item label="进货数量">
              <el-input-number v-model="receiveForm.quantity" :min="1"/>
            </el-form-item>
            <el-form-item label="单位">
              <el-input v-model="receiveForm.unit" placeholder="请输入单位"/>
            </el-form-item>
            <el-form-item label="价格">
              <el-input-number v-model="receiveForm.price" :min="0" placeholder="请输入价格"/>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="receiveForm.description" type="textarea" placeholder="请输入描述"/>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="handleReceiveGoods">提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="12">
        <el-table
            :data="allInventory"
            style="width: 100%"
            class="goods-table"
            border
        >
          <el-table-column prop="goods_name" label="商品名称" align="center"/>
          <el-table-column prop="current_quantity" label="当前数量" align="center"/>
          <el-table-column prop="min_quantity_alert" label="最小警报数量" align="center"/>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import {getInventoryItems as getAllInventory} from '@/api/inventory';
import {updateInventoryItem as updateInventoryStatus} from '@/api/inventory';
import {receiveGoods, generateInventoryReport} from '@/api/inventory'; // 引入新增的进货 API

export default {
  setup() {
    const allInventory = ref([]);
    const receiveForm = reactive({
      goodsName: '',
      quantity: null,
      unit: '',
      price: null,
      description: '',
    });

    const fetchInventory = async () => {
      try {
        const {data} = await getAllInventory();
        allInventory.value = data;
      } catch (error) {
        console.error('Failed to fetch inventory:', error);
        ElMessage.error('未能加载库存列表，请稍后重试。');
      }
    };

    const handleShelves = async (id) => {
      try {
        await updateInventoryStatus(id, {is_out_of_stock: false});
        ElMessage.success('商品已上架');
        fetchInventory();
      } catch (error) {
        ElMessage.error('上架失败，请稍后重试。');
      }
    };

    const handleUnshelves = async (id) => {
      try {
        await updateInventoryStatus(id, {is_out_of_stock: true});
        ElMessage.success('商品已下架');
        fetchInventory();
      } catch (error) {
        ElMessage.error('下架失败，请稍后重试。');
      }
    };

    const handleReceiveGoods = async () => {
      try {
        // 校验表单数据
        if (!receiveForm.goodsName || receiveForm.quantity <= 0) {
          ElMessage.error('商品名称不能为空，且数量必须大于 0');
          return;
        }

        // 获取 Token
        const token = localStorage.getItem('access');
        if (!token) {
          ElMessage.error('您还没有登录，请先登录！');
          return;
        }

        // 调用 API 添加商品或更新库存
        await receiveGoods({
          goods_name: receiveForm.goodsName,
          quantity: receiveForm.quantity,
          unit: receiveForm.unit, // 新增字段
          price: receiveForm.price, // 新增字段
          description: receiveForm.description, // 新增字段
        });

        // 成功提示
        ElMessage.success('进货成功！');
        // 重置表单
        receiveForm.goodsName = '';
        receiveForm.quantity = null;
        receiveForm.unit = ''; // 新增字段
        receiveForm.price = null; // 新增字段
        receiveForm.description = ''; // 新增字段

        // 刷新商品列表
        fetchInventory();
      } catch (error) {
        ElMessage.error('进货失败，请稍后重试。');
        console.error('Failed to receive goods:', error);
      }
    };

    // 新增导出报表方法
    const exportInventoryReport = async () => {
      try {
        await generateInventoryReport(); // 调用 API 导出报表
        ElMessage.success('库存报表导出成功，请前往报表管理下载。');
      } catch (error) {
        ElMessage.error('库存报表导出失败，请稍后重试。');
        console.error('Failed to export inventory report:', error);
      }
    };

    onMounted(fetchInventory);

    return {
      allInventory,
      handleShelves,
      handleUnshelves,
      receiveForm,
      handleReceiveGoods,
      exportInventoryReport
    };
  },
};
</script>